package com.fengba.nanzhi.tabbar03;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.PayTask;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.login.Login;
import com.fengba.nanzhi.myinfo.MyInfo;
import com.fengba.nanzhi.tabbar04.wz.AddressActivity;
import com.fengba.nanzhi.utils.Function;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by duan on 2018/4/25.
 */

public class SubmitOrder extends Activity {
    //屏幕的宽高
    private int screenWidth;
    private int screenHeight;
    //返回按钮
    private ImageButton back_btn;
    //背景界面
    private RelativeLayout mLayout;
    //状态栏
    private View statusBar;
    //标题栏
    private FrameLayout navigation_title;
    //滚动视图
    private SliderLayout mDemoSlider;
    //good数据
    private JSONObject goodObj;
    //地址添加按钮
    private ImageButton address_add_btn;
    //地址下一步
    private Button address_next_btn;
    //收货人姓名
    private TextView user_name;
    //收货人手机
    private TextView user_phone;
    //收货人的地址
    private TextView user_address;
    //good图片
    private ImageView good_image;
    //good名字
    private TextView good_name;
    //good价格
    private TextView good_price;
    //合计金额01
    private TextView total01;
    //合计金额02
    private TextView total02;
    //运费
    private TextView freight;
    //备注
    private TextView remake;
    //提交订单
    private Button sumit_btn;
    //滚动
    private ScrollView self_scrollview;
    //加
    private Button jia_btn;
    //减
    private Button jian_btn;
    //数量
    private TextView shop_num;
    //订单集合id
    private String orderid;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    //Log.e("obj",msg.obj.toString());
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(SubmitOrder.this, "支付成功", Toast.LENGTH_SHORT).show();
                        //String trade_no = data.getJSONObject("result").getJSONObject("alipay_trade_app_pay_response").getString("trade_no").toString();
                        try {
                            JSONObject data = new JSONObject(msg.obj.toString());
                            String r = data.getString("result").toString();
                            String alipay_trade_app_pay_response = new JSONObject(r).getString("alipay_trade_app_pay_response").toString();
                            String trade_no = new JSONObject(alipay_trade_app_pay_response).getString("trade_no").toString();
                            changeOrderStatus(trade_no);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(SubmitOrder.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(SubmitOrder.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(SubmitOrder.this,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    /**
     *Activity创建或者从被覆盖、后台重新回到前台时被调用
     */
    @Override
    protected void onResume() {
        super.onResume();
        //Log.e("ad","onResume is invoke!!!");
        getAddressInfo();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dmy_submitorder);

        bindViews();
        initStatusbarHeight();
        initBackgroundColor();
        setNavigationHeight();
        initData();
    }

    /**
     * 绑定所有的控件
     */
    private void bindViews(){
        //界面宽高
        screenWidth      = Function.getScreenWidth(this);
        screenHeight     = Function.getScreenHeight(this);
        //返回按钮
        back_btn         = findViewById(R.id.back_btn);
        //自己的layout
        mLayout          = findViewById(R.id.self_activity);
        //状态栏
        statusBar        = findViewById(R.id.view_statusbar);
        //导航栏
        navigation_title = findViewById(R.id.navigation_title);
        //地址添加按钮
        address_add_btn  = findViewById(R.id.address_add_btn);
        //地址下一步
        address_next_btn = findViewById(R.id.address_next_btn);
        //收货人姓名
        user_name        = findViewById(R.id.user_name);
        //收货人手机
        user_phone       = findViewById(R.id.user_phone);
        //收货人地址
        user_address     = findViewById(R.id.user_address);
        //商品图片
        good_image       = findViewById(R.id.good_img);
        //商品名字
        good_name        = findViewById(R.id.good_name);
        //商品价格
        good_price       = findViewById(R.id.good_price);
        //合计金额1
        total01          = findViewById(R.id.total01);
        //合计金额2
        total02          = findViewById(R.id.total02);
        //运费
        freight          = findViewById(R.id.freight);
        //备注
        remake           = findViewById(R.id.remake);
        //提交
        sumit_btn        = findViewById(R.id.sumit_btn);
        //滚动
        self_scrollview  = findViewById(R.id.self_scrollview);
        //加
        jia_btn          = findViewById(R.id.jia);
        //减
        jian_btn         = findViewById(R.id.jian);
        //购买的数量
        shop_num         = findViewById(R.id.shop_num);


        //返回上一页
        back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //点击键盘弹下来
        self_scrollview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mLayout.setFocusable(true);
                mLayout.setFocusableInTouchMode(true);
                mLayout.requestFocus();
                remake.clearFocus();//失去焦点
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mLayout.getWindowToken(), 0);
                return false;
            }
        });

        //跳转添加地址
        address_add_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SubmitOrder.this, AddressActivity.class);
                startActivity(intent);
            }
        });

        //加
        jia_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //商品
                String good = getIntent().getStringExtra("good");

                if(Integer.parseInt(shop_num.getText().toString())>=99){
                    return;
                }


                //数量
                int num = Integer.parseInt(shop_num.getText().toString());
                num++;
                try {
                    JSONObject myJson = new JSONObject(good.toString());
                    //限购
                    if(Integer.parseInt(shop_num.getText().toString())>=Integer.parseInt(myJson.get("single_number").toString())){
                        Toast.makeText(SubmitOrder.this,"对不起，每个人限购"+myJson.get("single_number").toString()+"个",Toast.LENGTH_LONG).show();
                        return;
                    }
                    shop_num.setText(String.valueOf(num));
                    //价格
                    Double price = Double.parseDouble(myJson.get("cfprice").toString());
                    //运费
                    Double freight = Double.parseDouble(myJson.get("freight").toString());
                    //计算
                    Double total = price*num+freight*num;
                    //total01
                    total01.setText("¥ "+ String.valueOf(Function.doubleToString(total)));
                    //total02
                    total02.setText("¥ "+ String.valueOf(Function.doubleToString(total)));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        //减
        jian_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(Integer.parseInt(shop_num.getText().toString())<=1){
                    return;
                }

                //数量
                int num = Integer.parseInt(shop_num.getText().toString());
                num--;
                shop_num.setText(String.valueOf(num));
                //商品
                String good = getIntent().getStringExtra("good");
                try {
                    JSONObject myJson = new JSONObject(good.toString());
                    //价格
                    Double price = Double.parseDouble(myJson.get("cfprice").toString());
                    //运费
                    Double freight = Double.parseDouble(myJson.get("freight").toString());
                    //计算
                    Double total01_d = price*num;
                    Double total02_d = price*num+freight*num;
                    //total01
                    total01.setText("¥ "+ String.valueOf(Function.doubleToString(total01_d)));
                    //total02
                    total02.setText("¥ "+ String.valueOf(Function.doubleToString(total02_d)));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        //结算
        sumit_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //地址是否完善
                if(!check01()){
                    return;
                }

                submitOrder();
            }
        });

        //添加地址
        address_add_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                check02();
            }
        });

    }

    /**
     * 初始化背景页颜色
     */
    private void initBackgroundColor(){
        mLayout.setBackgroundColor(Color.parseColor("#F7F7FC"));//使用颜色的16进制类型值
    }

    /**
     * 初始化背景页颜色
     */
    private void setNavigationHeight(){
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(0,0);
        params.width = screenWidth;
        params.height = Function.dip2px(this,44);
        params.topMargin = Function.getStatusBarHeight(this);
        navigation_title.setLayoutParams(params);
    }

    /**
     * 初始化数据
     */
    private void initData(){

        String good = getIntent().getStringExtra("good");
        try {

            //抽疯数据
            JSONObject myJson = new JSONObject(good.toString());
            ///////////////////////////////////////////////////商品图片
            JSONObject goodinfo = (JSONObject) myJson.get("goods");
            final String firstImg = goodinfo.get("images").toString().split(",")[0];
            //Log.e("aaaddd",firstImg);
            //图片下载
            OKManager.getInstance().asyncBitmapByUrl(firstImg, new OKManager.func3() {
                @Override
                public void onResponse(Bitmap bitmap) {
                    good_image.setImageBitmap(bitmap);
                }
            });
            //////////////////////////////////商品名字
            good_name.setText(myJson.get("goods_name").toString());
            ///////////////////////////////商品价格
            good_price.setText("¥ "+myJson.get("cfprice").toString());
            ///////////////////////////////合计金额01
            total01.setText("¥ "+myJson.get("cfprice").toString());
            ///////////////////////////////合计金额01
            total02.setText("¥ "+myJson.get("cfprice").toString());
            ///////////////////////////////运费
            freight.setText("¥ "+myJson.get("freight").toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void getAddressInfo(){
        Object user_info = Preferences.getParam(this,"user_info","");
        //address_add_btn.setVisibility(View.VISIBLE);
        if(user_info.toString().equals("")){
            address_add_btn.setVisibility(View.VISIBLE);
            address_next_btn.setVisibility(View.INVISIBLE);
            return;
        }
        try {
            JSONObject user_json = new JSONObject(user_info.toString());
            //账号
            String account = user_json.get("id").toString();
            //Log.e("account",account);
            OKManager.getInstance().type0003(account, new OKManager.func4() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    try {
                        //Log.e("sss",jsonObject.toString());
                        if(Integer.parseInt(jsonObject.get("code").toString()) == 0){
                            JSONArray dataArr = (JSONArray)jsonObject.get("data");
                            if(dataArr.length() == 0){
                                address_add_btn.setVisibility(View.VISIBLE);
                                address_next_btn.setVisibility(View.INVISIBLE);
                                return;
                            }
                            JSONObject addressObj = dataArr.getJSONObject(0);
                            //保存数据
                            Preferences.setParam(SubmitOrder.this,"default_address",addressObj.toString());
                            //姓名
                            user_name.setText(addressObj.get("receiver_name").toString());
                            //手机
                            user_phone.setText(addressObj.get("receiver_phone").toString());
                            //省
                            String province = addressObj.get("province").toString();
                            //市
                            String city = addressObj.get("city").toString();
                            //区
                            String district = addressObj.get("district").toString();
                            //地址
                            String address = addressObj.get("address").toString();
                            user_address.setText(province+city+district+address);

                            address_add_btn.setVisibility(View.INVISIBLE);
                            address_next_btn.setVisibility(View.VISIBLE);

                        }else{
                            String message = jsonObject.get("message").toString();
                            Toast.makeText(SubmitOrder.this, message, Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(String string) {
                    Toast.makeText(SubmitOrder.this, "网络错误", Toast.LENGTH_LONG).show();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化状态栏高度
     */
    private void initStatusbarHeight(){
        RelativeLayout.LayoutParams status_view_params = new RelativeLayout.LayoutParams(0,0);
        status_view_params.width = screenWidth;
        status_view_params.height = Function.getStatusBarHeight(this);
        statusBar.setLayoutParams(status_view_params);
    }

    /**
     * 判断是否有地址
     * @return
     */
    private boolean check01(){
         if(user_name.getText().toString().equals("") ||
                 user_phone.getText().toString().equals("") ||
                 user_address.getText().toString().equals("")){
             Toast.makeText(SubmitOrder.this, "请完善地址信息", Toast.LENGTH_LONG).show();
             return false;
         }

         return true;
    }

    /**
     * 判断是否登录
     * @return
     */
    private void check02(){
        try {
            Object account = Preferences.getParam(SubmitOrder.this,"account","");
            if(account != null && account != ""){
                Intent intent = new Intent(SubmitOrder.this,AddressActivity.class);
                startActivity(intent);
            }else{
                Intent intent = new Intent(SubmitOrder.this,Login.class);
                startActivity(intent);
            }
        }catch (Exception e){
            e.printStackTrace();
            Intent intent = new Intent(SubmitOrder.this,Login.class);
            startActivity(intent);
        }
    }

    private void submitOrder(){
        //获取地址信息
        Object object = Preferences.getParam(this,"default_address","");
        //用户信息
        Object user_info = Preferences.getParam(this,"user_info","");
        //抽疯信息
        String good = getIntent().getStringExtra("good");
        try {
            JSONObject default_address = new JSONObject(object.toString());
            JSONObject user_json = new JSONObject(user_info.toString());
            JSONObject good_json = new JSONObject(good.toString());
            JSONObject goodinfo = (JSONObject) good_json.get("goods");
            //用户id
            String user_id = user_json.get("id").toString();
            //地址id
            String address_id = default_address.get("id").toString();
            //商品id
            String good_id = goodinfo.get("id").toString();
            //购买数量
            String num = shop_num.getText().toString();
            //备注
            String remarks = remake.getText().toString();
            //类型
            String type = "1";
            //活动编号
            String activity_number = good_json.get("crazy_number").toString();
            //拼手气规则编号
            String crazyrob_id = "0";
            //购买最终价格
            String total = total02.getText().toString().substring(2);
            //豆豆数
            String credit = "0";

            OKManager.getInstance().type0005(user_id, address_id, total, good_id, num, remarks,activity_number, type, credit, crazyrob_id, new OKManager.func4() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    //Log.e("111",jsonObject.toString());
                    try {
                        if(Integer.parseInt(jsonObject.get("code").toString()) == 0){
                            JSONObject data = jsonObject.getJSONObject("data");
                            orderid = data.getString("order_id").toString();
                            String message = jsonObject.get("message").toString();
                            Toast.makeText(SubmitOrder.this, message, Toast.LENGTH_LONG).show();
                        }else{
                            String message = jsonObject.get("message").toString();
                            Toast.makeText(SubmitOrder.this, message, Toast.LENGTH_LONG).show();
                        }

                        // 支付
                        new Handler().postDelayed(new Runnable(){
                            public void run() {
                                //Ljuhua.setVisibility(ProgressBar.INVISIBLE);
                                //finish();
                                doPay();
                            }
                        }, 250);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(SubmitOrder.this, "网络错误", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure(String string) {

                }
            });


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void doPay(){
        //用户信息
        Object user_info = Preferences.getParam(this,"user_info","");
        try {
            JSONObject user_json = new JSONObject(user_info.toString());
            //用户id
            String user_id = user_json.get("id").toString();
            //卡号
            String card_number = "0";
            //购买最终价格
            String total = total02.getText().toString().substring(2);

            OKManager.getInstance().type0006(user_id, card_number, total, new OKManager.func4() {
                @Override
                public void onResponse(final JSONObject jsonObject) {
                    final JSONObject temp = jsonObject;
                    //Log.e("111",jsonObject.toString());
                    try {
                        if(Integer.parseInt(jsonObject.get("code").toString()) == 0){
                            Runnable payRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        // PayTask 对象
                                        PayTask alipay = new PayTask(SubmitOrder.this);
                                        Map<String, String> result = null;
                                        result = alipay.payV2(temp.get("data").toString(), true);
                                        //Log.i("msp", result.toString());

                                        Message msg = new Message();
                                        msg.what = SDK_PAY_FLAG;
                                        msg.obj = result;
                                        mHandler.sendMessage(msg);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }
                            };
                            // 必须异步调用
                            Thread authThread = new Thread(payRunnable);
                            authThread.start();
                        }else{
                            String message = jsonObject.get("message").toString();
                            Toast.makeText(SubmitOrder.this, message, Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(SubmitOrder.this, "网络错误", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure(String string) {

                }
            });


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改订单状态
     */
    private void changeOrderStatus(String out_trade_no){
        //用户信息
        Object user_info = Preferences.getParam(this,"user_info","");
        try {
            JSONObject user_json = new JSONObject(user_info.toString());
            //用户id
            String user_id = user_json.get("id").toString();
            //类型
            String type = "1";
            //订单id
            String order_id = this.orderid;

            OKManager.getInstance().type0007(user_id, order_id, type, out_trade_no, new OKManager.func4() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    //Log.e("111",jsonObject.toString());
                    try {
                        if(Integer.parseInt(jsonObject.get("code").toString()) == 0){
                            String message = jsonObject.get("message").toString();
                            Toast.makeText(SubmitOrder.this, message, Toast.LENGTH_LONG).show();
                        }else{
                            String message = jsonObject.get("message").toString();
                            Toast.makeText(SubmitOrder.this, message, Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(SubmitOrder.this, "网络错误", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure(String string) {

                }
            });


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
